package mia.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateManager {

	static private Configuration cfg;
	static private ServiceRegistry svRegistry;
	static private SessionFactory sessionFactory;
	
	static{
		cfg = new Configuration().configure();
		svRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		sessionFactory = cfg.buildSessionFactory(svRegistry);
	}
	
	public static Session getSession()
	{
		return sessionFactory.openSession();
	}
	
	public static boolean trySave(Object ...objects)
	{
		Session session = HibernateManager.getSession();
		session.beginTransaction();
		try
		{
			for(Object o : objects)
				session.save(o);
			session.getTransaction().commit();
			return true;
		}
		catch(Exception ex)
		{
			session.getTransaction().rollback();
			return false;
		}
		finally
		{
			session.close();
		}
	}
	
	public static boolean tryMerge(Object ...objects)
	{
		Session session = HibernateManager.getSession();
		session.beginTransaction();
		try
		{
			for(Object o : objects)
				session.merge(o);
			session.getTransaction().commit();
			return true;
		}
		catch(Exception ex)
		{
			session.getTransaction().rollback();
			return false;
		}
		finally
		{
			session.close();
		}
	}
}
